import requests
from bs4 import BeautifulSoup

from twitter.api import Twitter
from twitter.oauth import OAuth, write_token_file


def auto_oauth_dance(app_name, consumer_key, consumer_secret, user_name, pwd, token_filename=None):
    """
    Perform the OAuth dance with some command-line prompts. Return the
    oauth_token and oauth_token_secret.

    Provide the name of your app in `app_name`, your consumer_key, and
    consumer_secret. This function will open a web browser to let the
    user allow your app to access their Twitter account. PIN
    authentication is used.

    If a token_filename is given, the oauth tokens will be written to
    the file.
    """
    print("Hi there! We're gonna get you all set up to use %s." % app_name)
    twitter = Twitter(
        auth=OAuth('', '', consumer_key, consumer_secret),
        format='', api_version=None)
    oauth_token, oauth_token_secret = parse_oauth_tokens(
        twitter.oauth.request_token(oauth_callback="oob"))
    print("""
In the web browser window that opens please choose to Allow
access. Copy the PIN number that appears on the next page and paste or
type it here:
""")
    oauth_url = ('https://api.twitter.com/oauth/authorize?oauth_token=' +
                 oauth_token)
    print("auto Opening: %s\n" % oauth_url)

    oauth_verifier = get_pin(oauth_url, oauth_token, user_name, pwd)
    twitter = Twitter(
        auth=OAuth(
            oauth_token, oauth_token_secret, consumer_key, consumer_secret),
        format='', api_version=None)
    oauth_token, oauth_token_secret = parse_oauth_tokens(
        twitter.oauth.access_token(oauth_verifier=oauth_verifier))
    if token_filename:
        write_token_file(
            token_filename, oauth_token, oauth_token_secret)

        print("That's it! Your authorization keys have been written to %s." % (
            token_filename))
    return oauth_token, oauth_token_secret


def parse_oauth_tokens(result):
    for r in result.split('&'):
        k, v = r.split('=')
        if k == 'oauth_token':
            oauth_token = v
        elif k == 'oauth_token_secret':
            oauth_token_secret = v
    return oauth_token, oauth_token_secret


def get_pin(url, oauth_token, user_name, pwd):
    header = {'Content-Type': 'application/x-www-form-urlencoded',
              'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0',
              }
    s = requests.session()
    s.headers.update(header)
    r = s.get(url)
    soup = BeautifulSoup(r.text, 'html5lib')
    authenticity_token = soup.find('input', attrs={'name':'authenticity_token'})['value']
    post_data = {'authenticity_token': authenticity_token,
                 'redirect_after_login': url,
                 'oauth_token': oauth_token,
                 'session[username_or_email]': user_name,
                 'session[password]': pwd}
    r = s.post('https://api.twitter.com/oauth/authorize', data=post_data, headers=header)
    soup = BeautifulSoup(r.text, 'html5lib')
    pin = soup.find('code').string
    if pin:
        print('successful get pin')
    return pin
